package com.blinddate.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blinddate.mapper.UserMapper;
import com.blinddate.pojo.entity.User;
import com.blinddate.properties.WeChatProperties;
import com.blinddate.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    public User wxlogin(String code) {
        //使用微信接口服务来获取小程序的openid
        String openid=getOpenid(code);

        //openid为空 登录失败 抛出异常
        if(openid==null){
            return null;
        }
        //判断当前用户是否为新用户
        LambdaQueryWrapper<User> qw=new LambdaQueryWrapper<User>();
        qw.eq(User::getOpenId,openid);
        User user=userMapper.selectOne(qw);
        log.info("{}",user);
        //如果是新用户 自动完成注册
        if(user==null){
            user=User.builder()
                    .openId(openid)
                    .build();
            userMapper.insert(user);
        }
        return user;
        //返回用户
    }
    private String getOpenid(String code){
        Map<String,String> map= new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json= HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject= JSON.parseObject(json);
        return jsonObject.getString("openid");
    }

}
